package com.woniuxy.health.manager.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.health.manager.dto.AuthorizationDto;
import com.woniuxy.health.manager.dto.RolePermissionDto;
import com.woniuxy.health.manager.mapper.RolePermissionMapper;
import com.woniuxy.health.model.manager.RolePermission;
import com.woniuxy.health.manager.service.IRolePermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author woniuxy
 * @since 2023-09-04
 */
@Service
public class RolePermissionServiceImpl extends ServiceImpl<RolePermissionMapper, RolePermission> implements IRolePermissionService {

    private final RolePermissionMapper rolePermissionMapper;

    @Autowired
    public RolePermissionServiceImpl(RolePermissionMapper rolePermissionMapper){
        this.rolePermissionMapper = rolePermissionMapper;
    }

    @Override
    public void roleAuthorization(RolePermissionDto rolePermissionDto) {
        //先删除原有的权限
        rolePermissionMapper.delete(Wrappers.lambdaQuery(RolePermission.class)
                .eq(RolePermission::getRoleId,rolePermissionDto.getId()));
        //再新增新的权限
        rolePermissionDto.getPermissionData().forEach(id -> {
            RolePermission rolePermission = new RolePermission();
            rolePermission.setRoleId(rolePermissionDto.getId());
            rolePermission.setPerssionId(id);
            rolePermissionMapper.insert(rolePermission);
        });
    }

    @Override
    public void roleAuthorization2(RolePermissionDto rolePermissionDto) {
        List<RolePermission> rolePermissions = rolePermissionMapper.selectList(Wrappers.lambdaQuery(RolePermission.class)
                .eq(RolePermission::getRoleId, rolePermissionDto.getId()));
        List<Long> permissionIds = rolePermissions.stream().map(e -> e.getPerssionId()).collect(Collectors.toList());
        //如果数据库中的角色已有的权限id中没有前端选中的权限id，就给角色添加这个权限
        rolePermissionDto.getPermissionData().forEach(id -> {
            if (!permissionIds.contains(id)){
                RolePermission rolePermission = new RolePermission();
                rolePermission.setRoleId(rolePermissionDto.getId());
                rolePermission.setPerssionId(id);
                rolePermissionMapper.insert(rolePermission);
            }
        });
        //如果前端选中的权限id中没有数据库中的权限id，就删除该角色在数据库中对应的权限
        rolePermissionMapper.delete(Wrappers.lambdaQuery(RolePermission.class)
                .eq(Objects.nonNull(rolePermissionDto.getId()),RolePermission::getRoleId, rolePermissionDto.getId())
                .notIn(!rolePermissionDto.getPermissionData().isEmpty(),RolePermission::getPerssionId, rolePermissionDto.getPermissionData()));
    }
}
